package com.ef.web.action;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.Border;
import jxl.write.BorderLineStyle;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;

import org.apache.struts2.ServletActionContext;
import org.hibernate.Criteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import com.ef.constant.EPayType;
import com.ef.constant.StatusType;
import com.ef.domain.CorpClass;
import com.ef.domain.CorpContract;
import com.ef.domain.CorpPayHistory;
import com.ef.domain.Leads;
import com.ef.service.CorpClassService;
import com.ef.service.CorpContractService;
import com.ef.service.CorpPayService;
import com.ef.util.CustomExample;

public class CorpPayAction extends BaseAction<CorpContract> {

	private static final long serialVersionUID = 1L;

	protected final org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory
			.getLog(CorpPayAction.class);

	private CorpContractService corpContractService;

	private CorpPayService corpPayService;

	private String selCompanyId;

	private String payMoney;

	private Date payTime;

	private String payComment;

	private String refMoney;

	private Date refTime;

	@Temporal(TemporalType.TIMESTAMP)
	private Date selPayStartTime;

	@Temporal(TemporalType.TIMESTAMP)
	private Date selPayEndTime;

	public Date getSelPayStartTime() {
		return selPayStartTime;
	}

	public void setSelPayStartTime(Date selPayStartTime) {
		this.selPayStartTime = selPayStartTime;
	}

	public Date getSelPayEndTime() {
		return selPayEndTime;
	}

	public void setSelPayEndTime(Date selPayEndTime) {
		this.selPayEndTime = selPayEndTime;
	}

	public Date getPayTime() {
		return payTime;
	}

	public void setPayTime(Date payTime) {
		this.payTime = payTime;
	}

	public Date getRefTime() {
		return refTime;
	}

	public void setRefTime(Date refTime) {
		this.refTime = refTime;
	}

	private String refComment;

	private List<CorpPayHistory> corpPayHistoryList;

	private CorpClassService corpClassService;

	private List<CorpClass> corpClassList;

	private String selCompanyName;

	@SuppressWarnings("serial")
	public String list() {
		this.listResult = corpContractService.findByExample(
				new CustomExample<CorpContract>(this.getModel()) {
					public void appendCondition(Criteria criteria) {
						if ((selCompanyName != null && selCompanyName.trim()
								.length() > 0)) {
							criteria.createAlias("company", "company");
							criteria.add(Restrictions
											.like("company.name",
													selCompanyName.trim(),
													MatchMode.ANYWHERE));
						}
						criteria.add(Restrictions
								.eq("status", StatusType.VALID));
						this.enableLike(MatchMode.ANYWHERE);
					}
				}, this.getStartIndex(), this.getPageSize());
		return LIST;
	}

	public String edit() {
		fetchListData();
		return EDIT;
	}

	public String view() {
		fetchListData();
		return VIEW;
	}

	private void fetchListData() {
		if (this.getModel().getId() != null
				&& this.getModel().getCompany() != null) {
			this.selCompanyId = this.getModel().getCompany().getId().toString();
		}

		if (this.getModel().getId() != null) {
			corpPayHistoryList = corpPayService.findByContract(this.getModel());
			corpClassList = corpClassService.findByContract(this.getModel());
		}
	}

	public String pay() {
		CorpContract cont = this.getModel();
		CorpPayHistory pay = new CorpPayHistory();
		pay.setComments(this.payComment);
		pay.setPay(Double.valueOf(payMoney.trim()));
		pay.setContract(cont);
		pay.setPayTime(this.payTime);
		pay.setPayType(EPayType.Pay);
		pay.setPayUser(getSessionUser());
		corpPayService.saveOrUpdate(pay);
		if (cont.getPaidMoney() == null) {
			cont.setPaidMoney(Double.valueOf(payMoney.trim()));
		} else {
			cont.setPaidMoney(Double.valueOf(payMoney.trim())
					+ cont.getPaidMoney());
		}
		corpContractService.saveOrUpdate(cont);
		fetchListData();
		return VIEW;
	}

	public String refund() {
		CorpContract cont = this.getModel();
		CorpPayHistory pay = new CorpPayHistory();
		pay.setComments(this.refComment);
		pay.setPay(Double.valueOf(refMoney.trim()));
		pay.setContract(cont);
		pay.setPayTime(this.refTime);
		pay.setPayType(EPayType.Refund);
		pay.setPayUser(getSessionUser());
		corpPayService.saveOrUpdate(pay);
		if (cont.getPaidMoney() == null) {
			cont.setPaidMoney(0d);
		} else {
			cont.setPaidMoney(cont.getPaidMoney()
					- Double.valueOf(refMoney.trim()));
		}
		corpContractService.saveOrUpdate(cont);
		fetchListData();
		return VIEW;
	}

	public String getPayMoney() {
		return payMoney;
	}

	public void setPayMoney(String payMoney) {
		this.payMoney = payMoney;
	}

	public String getRefMoney() {
		return refMoney;
	}

	public void setRefMoney(String refMoney) {
		this.refMoney = refMoney;
	}

	public String getRefComment() {
		return refComment;
	}

	public void setRefComment(String refComment) {
		this.refComment = refComment;
	}

	public String getPayComment() {
		return payComment;
	}

	public void setPayComment(String payComment) {
		this.payComment = payComment;
	}

	public CorpContractService getCorpContractService() {
		return corpContractService;
	}

	public void setCorpContractService(CorpContractService corpContractService) {
		this.corpContractService = corpContractService;
	}

	public CorpPayService getCorpPayService() {
		return corpPayService;
	}

	public void setCorpPayService(CorpPayService corpPayService) {
		this.corpPayService = corpPayService;
	}

	public String getSelCompanyId() {
		return selCompanyId;
	}

	public void setSelCompanyId(String selCompanyId) {
		this.selCompanyId = selCompanyId;
	}

	public List<CorpPayHistory> getCorpPayHistoryList() {
		return corpPayHistoryList;
	}

	public void setCorpPayHistoryList(List<CorpPayHistory> corpPayHistoryList) {
		this.corpPayHistoryList = corpPayHistoryList;
	}

	public String getSelCompanyName() {
		return selCompanyName;
	}

	public void setSelCompanyName(String selCompanyName) {
		this.selCompanyName = selCompanyName;
	}

	public CorpClassService getCorpClassService() {
		return corpClassService;
	}

	public void setCorpClassService(CorpClassService corpClassService) {
		this.corpClassService = corpClassService;
	}

	public List<CorpClass> getCorpClassList() {
		return corpClassList;
	}

	public void setCorpClassList(List<CorpClass> corpClassList) {
		this.corpClassList = corpClassList;
	}

	public String export() {

		if (selPayStartTime == null) {
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
			String start = format.format(new Date());
			try {
				selPayStartTime = format.parse(start + "-01");
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		if (selPayEndTime == null) {
			selPayEndTime = new Date();
		}

		List<CorpPayHistory> result = corpPayService.findByPayTime(
				selPayStartTime, selPayEndTime);
		if (result.size() < 1)
			return NONE;
		HttpServletRequest request = getRequest();
		HttpServletResponse response = getResponse();

		response.setContentType("application/ms-excel;charset=UTF-8");
		response.setHeader("Content-Disposition",
				"attachment;filename=CorpPay.xls");

		File tempPath = new File(ServletActionContext.getServletContext()
				.getRealPath("/temp"));
		if (!tempPath.exists()) {
			tempPath.mkdirs();
		}
		WritableWorkbook workBook;

		File exportFile = new File(ServletActionContext.getServletContext()
				.getRealPath("/temp/CorpPay.xls"));
		try {
			// TODO styles
			WritableFont font = new WritableFont(WritableFont.TIMES, 12,
					WritableFont.BOLD);
			WritableCellFormat headStyle = new WritableCellFormat(font);
			headStyle.setAlignment(Alignment.CENTRE);
			WritableCellFormat titleStyle = new WritableCellFormat(font);
			titleStyle.setAlignment(Alignment.CENTRE);
			titleStyle.setWrap(false);
			titleStyle.setBorder(Border.ALL, BorderLineStyle.THIN);
			WritableFont font_content = new WritableFont(WritableFont.TIMES, 10);
			WritableCellFormat contentStyle = new WritableCellFormat(
					font_content);
			contentStyle.setAlignment(Alignment.CENTRE);
			contentStyle.setBorder(Border.ALL, BorderLineStyle.THIN);
			contentStyle.setWrap(false);
			workBook = Workbook.createWorkbook(exportFile);
			workBook.setProtected(false);

			// create sheets
			WritableSheet activeSheet = workBook.createSheet("sheet", 0);
			activeSheet.addCell(new Label(0, 1, "序号 ", titleStyle));
			activeSheet
					.addCell(new Label(1, 1, "     付款日期        ", titleStyle));
			activeSheet
					.addCell(new Label(2, 1, "    公司名称        ", titleStyle));
			activeSheet.addCell(new Label(3, 1, "Cash ", titleStyle));
			activeSheet.addCell(new Label(4, 1, "Card", titleStyle));
			activeSheet.addCell(new Label(5, 1, "     Chepue    ", titleStyle));
			activeSheet.addCell(new Label(6, 1, "     说明        ", titleStyle));
			activeSheet.addCell(new Label(7, 1, "实际收实金额 ", titleStyle));
			activeSheet.addCell(new Label(8, 1, "书费", titleStyle));
			activeSheet.addCell(new Label(9, 1, "交通费 ", titleStyle));
			activeSheet.addCell(new Label(10, 1, "业绩 ", titleStyle));
			activeSheet.addCell(new Label(11, 1, "CLT ", titleStyle));
			activeSheet.addCell(new Label(12, 1, "备注 ", titleStyle));
			int size = result.size();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd");
			int curRowIndex = 2;
			int j=1;
			for (CorpPayHistory curPay:result) {
				activeSheet.addCell(new Label(0, curRowIndex, String
						.valueOf(j++), contentStyle));
				activeSheet.addCell(new Label(1, curRowIndex, sdf.format(curPay
						.getPayTime()), contentStyle));
				activeSheet.addCell(new Label(2, curRowIndex, curPay
						.getContract().getCompany().getName(), contentStyle));
				activeSheet
						.addCell(new Label(3, curRowIndex, "", contentStyle));
				activeSheet
						.addCell(new Label(4, curRowIndex, "", contentStyle));
				String pay=curPay
				.getContract().getPrice().toString();
				if (curPay.getPayType().equals(EPayType.Refund)){
					pay="-"+curPay
					.getContract().getPrice().toString();
				}
				activeSheet.addCell(new Label(5, curRowIndex,pay, contentStyle));
				activeSheet.addCell(new Label(6, curRowIndex, curPay
						.getComments(), contentStyle));
				activeSheet.addCell(new Label(7, curRowIndex, curPay.getPay()
						.toString(), contentStyle));
				activeSheet
						.addCell(new Label(8, curRowIndex, "", contentStyle));
				activeSheet
						.addCell(new Label(9, curRowIndex, "", contentStyle));
				activeSheet
						.addCell(new Label(10, curRowIndex, "", contentStyle));
				String clt = "";
				if (curPay.getContract().getCompany().getCc() != null) {
					clt = curPay.getContract().getCompany().getCc().getName();
				}
				activeSheet.addCell(new Label(11, curRowIndex, clt,
						contentStyle));
				activeSheet.addCell(new Label(12, curRowIndex, curPay
						.getContract().getComments(), contentStyle));
				curRowIndex++;
			}
			workBook.write();
			workBook.close();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (WriteException e) {
			e.printStackTrace();
		}
		RequestDispatcher dispatcher = request
				.getRequestDispatcher("../../temp/CorpPay.xls");
		try {
			dispatcher.forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return NONE;
	}
}
